package org.example.auth.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import org.example.auth.api.MemberService;
import org.example.auth.api.module.LoginMember;
import org.example.auth.constant.RequestConstants;
import org.example.auth.constant.VxTokenConstants;
import org.example.auth.properties.VxProperties;
import org.example.auth.service.VxLoginService;
import org.example.core.constant.TokenConstants;
import org.example.core.utils.JwtUtils;
import org.example.core.utils.OkHttpUtils;
import org.example.core.utils.R;
import org.example.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author 小杰_cc
 * @version 1.0
 */
@Service
public class VxLoginServiceImpl implements VxLoginService {

    @Autowired
    private VxProperties vxProperties;
    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisService redisService;

    @Override
    public R<String> vxLogin(String code) {
        // 获取access_token
        String accessToken = redisService.getObject(VxTokenConstants.ACCESS_TOKEN);
        if(StrUtil.isBlank(accessToken)){
            HashMap<String, String> params = new HashMap<>();
            params.put("grant_type", "client_credential");
            params.put("appid", vxProperties.getAppid());
            params.put("secret", vxProperties.getSecret());
            // 发送请求
            String respToken = OkHttpUtils.post(RequestConstants.TOKEN_URL, params);
            // access_token
            accessToken = (String) JSON.parseObject(respToken).get("access_token");
            // 缓存access_token
            redisService.setObject(VxTokenConstants.ACCESS_TOKEN, accessToken, VxTokenConstants.expiresTime, TimeUnit.SECONDS);
        }

        // 获取手机号
        HashMap<String, String> param = new HashMap<>();
        param.put("code", code);
        String respPhone = OkHttpUtils.post(RequestConstants.PHONE_URL + accessToken, param);
        String phoneNumber = (String) JSON.parseObject(respPhone).getJSONObject("phone_info").get("phoneNumber");
        R<LoginMember> member = memberService.login(phoneNumber);
        if (member.getCode() != 0){
            return R.error("登录失败请稍后再试");
        }
        LoginMember loginMember = member.getData();
        if(loginMember.getStatus() == 1){
            return R.error("抱歉账号已被禁用，请联系客服解决");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put(TokenConstants.MEMBER_ID, loginMember.getId());
        map.put(TokenConstants.MEMBER_NAME, loginMember.getUsername());
        // 返回token
        return R.ok(JwtUtils.createMemberToken(map));
    }
}
